<?php

namespace Henan\ThinkSdk\service;


use bingher\ding\DingBot;
use Exception;
use Henan\ThinkSdk\helper\FC;
use think\facade\Config;

/**
 * 钉钉机器人服务类
 * @author henan
 */
class DingBotService
{
    /**
     * 构造函数
     * @param array $config
     */
    public function __construct(public array $config = [])
    {
        if (empty($this->config)) $this->config = Config::get('sdk.DingBotService');
    }

    /**
     * 钉钉机器人消息发送
     * @param string $title
     * @param  $content
     * @param string $bot
     * @return void
     * @throws Exception
     */
    public function send(string $title, $content, string $bot = 'default'): void
    {
        try {
            is_array($content) && $content = json_encode($content, 320);
            $content = FC::getDomain() . PHP_EOL . $title . PHP_EOL . $content . PHP_EOL . FC::getUrl();
            $this->sendText($content, $bot);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 发送文本消息
     * @param string $content
     * @param string $bot
     * @return void
     * @throws Exception
     */
    public function sendText(string $content, string $bot = 'default'): void
    {
        try {
            $ding = new DingBot($this->config[$bot]);
            $ding->text($content);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }
}